import Qfpage from "../../components/Qfpage/Qfpage";
import { 
    Button,
    Drawer, 
    Form,
    Table,
    Input ,
    InputNumber,
    message,
    Modal,
    Row,
    Col,
} from 'antd'

import { useMemo ,useEffect,useState, useRef,useLayoutEffect} from "react";
import {  getAllType ,addType ,delType,editType }  from '../../api/roomType'
const Room = ()=>{

    const [data,setData] = useState([]);
    const [limit,setLimit] = useState(30);  // 单页数量
    const [page,setPage] = useState(1); 
    const [total ,setTotal] = useState(0); // 总数
   // 获取表格数据的主函数
    const getData = async ()=>{
        const postData = { limit,page };
        if(name) postData.name = name;
        if(price) postData.price = price;

        let res = await getAllType(postData)
        const {  success ,data, count} = res;
        if(success) {
            setData(data);
            setTotal(count)
        };   
    }
 
    // 条件过滤
    const [name,setName] = useState('');
    const [price,setPrice] =useState('')
    

    useLayoutEffect(()=>{
        getData();
    },[limit,page])


    const confirmDel = async (id)=>{
        let res = await delType({typeid: id});
        const  {success} = res;
        if(!success) return  message.warning('删除失败')
        message.success('删除成功');
        getData();
    }

    const handlerDel =  (id)=>{
        const delDialog = Modal({
            header: '提醒',
            body: '你确定要删除当前的房型吗？',
            onConfirm: ()=>{
                delDialog.hide();
                confirmDel(id); // 执行删除
            } , 
            onClose: ({ e, trigger }) => {
                delDialog.hide()
            },
        });
    }

    const columns = useMemo(()=>[
            {   title:'房型名称', colKey:'name' },
            {   title:'床数量', colKey:'beds'   },
            {   title:'价格', colKey:'price'   },
            {   
                title:'押金', 
                colKey:'yaPrice' ,
                cell({row}){
                    return row.yaPrice || '无'
                }
            },
            {   title:'简称', colKey:'shortName'   },
            {   title:'入住人数', colKey:'liveLimit'   },
            {   title:'早餐券数量', colKey:'couponNum'   },
            {   title:'操作', colKey:'colKey',
                cell:({row})=>{  // 这一列的是通过cell的方法来返回的值进行渲染的
                
                    return <> 
                                <Button  variant="outline" size="small" onClick={()=>handlerDel(row._id)}>删除</Button> 
                                <Button variant="outline"  style={{marginLeft:'5px'}} size="small" onClick={()=>openEdit(row)}>修改</Button> 
                         </>
                }
            }
    ],[])


    const formRef = useRef(null)


    // 添加房型的操作
    
    const rules = {// 表单的校验规则
        name: [ { required:true,message:'不可能不填吧',type:'error' }],
        price: [ { required:true,message:'不可能不填吧',type:'error' }]
    } 
            
    
    const [showAdd,setShowAdd] = useState(false)
    const handleAdd   = async ()=>{
        const okornot = await formRef.current.validate() // 表单验证 通过的话返回true
        if(okornot !== true) return ;
        const values = formRef.current.getFieldsValue(true); // 得到所有的表单的值
        console.log('values',values)
        let res = await addType(values);
        const { success } = res;
        if(!success) return message.warning('添加失败');
        message.success('添加成功');
        getData(); // 刷新表格
        formRef.current.reset(); // 重置表单
        setShowAdd(false) // 抽屉隐藏
    }



    // 修改房型的操作

    const [showEdit,setShowEdit] = useState(false);
    const editRef = useRef(null);
    const [curRow,setCurRow] = useState(null)
    const openEdit = (row)=>{
        setCurRow(row)
        // 设置 修改表单的内容
        editRef.current.setFieldsValue(row)
        setShowEdit(true); //  让修改抽屉弹出
    }
    const handleEdit   = async ()=>{
        const okornot = await editRef.current.validate() // 表单验证 通过的话返回true
        if(okornot !== true) return ;
        const values = editRef.current.getFieldsValue(true); // 得到所有的表单的值
        // 发送请求执行修改
        let res = await editType({
            ...values,
            typeid:curRow._id
        });
        const { success } = res;
        if(!success) return message.warning('修改失败');
        message.success('修改成功');
        getData(); // 刷新表格
        setShowEdit(false) // 抽屉隐藏
    }




    return (
        <Qfpage title="房型维护">
           
         <div style={{padding:'15px'}}> 

          <Row>
            <Col span={3}>
                 {/* 操作区域 */}
                 <Button onClick={()=> setShowAdd(true) }>添加新的房型</Button>
            </Col>
            <Col span={1}></Col>
            <Col span={6}>
                <Input.Group>
                    <Input placeholder="输入你有查询的房型" onChange={setName}  /> 
                    <Input placeholder="按价格查询" onChange={setPrice} />
                </Input.Group>
            </Col>
            <Col span={2}>
                <Button onClick={getData}>立即查询</Button>
            </Col>
          </Row>
         
          
          
         </div>
           <Table
                columns={columns} 
                data={data} 
                pagination={{
                    defaultPageSize: limit,
                    total,
                    onChange({pageSize,current}){
                       setPage(current);
                       setLimit(pageSize)
                 
                    }
                  }}
            /> 

           {/* 添加房型的 抽屉 */}
           <Drawer 
                visible={showAdd} 
                size="600px" 
                onClose={()=> setShowAdd(false) } 
                confirmBtn="立即添加"
                onConfirm={handleAdd}
            >
                 <Form ref={formRef} rules={rules}> 
                    <Form.Item label="房型名称" name="name">
                        <Input  placeholder="填写房型名称" />
                    </Form.Item>
                    <Form.Item label="房型简称" name="shortName">
                        <Input  placeholder="填写房间简称" />
                    </Form.Item>


                    <Form.Item label="入住人数" name="liveLimit">
                        <InputNumber
                                autoWidth={false}
                                decimalPlaces={undefined}
                                max={Infinity}
                                min={1}
                                readonly={false}
                                size="medium"
                                step={1}
                                theme="row"
                                defaultValue={1}
                        />
                    </Form.Item>
                    <Form.Item label="床数" name="beds">
                        <InputNumber
                            autoWidth={false}
                            decimalPlaces={undefined}
                            max={Infinity}
                            min={1}
                            readonly={false}
                            size="medium"
                            step={1}
                            theme="row"
                            defaultValue={1}
                        />
                    </Form.Item>
                    <Form.Item label="价格" name="price">
                        <Input  placeholder="填写价格"/>
                    </Form.Item>
                    <Form.Item label="押金" name="yaPrice">
                        <Input  placeholder="填写押金"/>
                    </Form.Item>

                    <Form.Item label="早餐券数量" name="couponNum">
                        <InputNumber
                                autoWidth={false}
                                decimalPlaces={undefined}
                                max={Infinity}
                                min={0}
                                readonly={false}
                                size="medium"
                                step={1}
                                theme="row"
                                defaultValue={0}
                        />
                    </Form.Item>
                    <Button 
                            style={{ margin: '0 24px 0 0', }}
                            onClick={handleAdd}
                        >
                            立即添加
                    </Button>
                    <Button onClick={setShowAdd}>取消</Button>



                 </Form>


           </Drawer>


           {/* 修改房型的抽屉 */}
           <Drawer 
                visible={showEdit} 
                size="600px" 
                onClose={()=> setShowEdit(false) } 
                confirmBtn="立即修改"
                onConfirm={handleEdit}
            >
                 <Form ref={editRef} rules={rules}> 
                    <Form.Item label="房型名称" name="name">
                        <Input  placeholder="填写房型名称" />
                    </Form.Item>
                    <Form.Item label="房型简称" name="shortName">
                        <Input  placeholder="填写房间简称" />
                    </Form.Item>


                    <Form.Item label="入住人数" name="liveLimit">
                        <InputNumber
                                autoWidth={false}
                                decimalPlaces={undefined}
                                max={Infinity}
                                min={1}
                                readonly={false}
                                size="medium"
                                step={1}
                                theme="row"
                                defaultValue={1}
                        />
                    </Form.Item>
                    <Form.Item label="床数" name="beds">
                        <InputNumber
                            autoWidth={false}
                            decimalPlaces={undefined}
                            max={Infinity}
                            min={1}
                            readonly={false}
                            size="medium"
                            step={1}
                            theme="row"
                            defaultValue={1}
                        />
                    </Form.Item>
                    <Form.Item label="价格" name="price">
                        <Input  placeholder="填写价格"/>
                    </Form.Item>
                    <Form.Item label="押金" name="yaPrice">
                        <Input  placeholder="填写押金"/>
                    </Form.Item>

                    <Form.Item label="早餐券数量" name="couponNum">
                        <InputNumber
                                autoWidth={false}
                                decimalPlaces={undefined}
                                max={Infinity}
                                min={0}
                                readonly={false}
                                size="medium"
                                step={1}
                                theme="row"
                                defaultValue={0}
                        />
                    </Form.Item>

                    <Button 
                            style={{ margin: '0 24px 0 0', }}
                            onClick={handleAdd}
                        >
                            立即添加
                    </Button>
                    <Button onClick={setShowAdd}>取消</Button>
                    
                 </Form>
           </Drawer>
        </Qfpage>
      
    )
}

export default Room;